package com.zahb.qadx.ui.fragment;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterViewFlipper;
import android.widget.FrameLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.widget.LinearLayoutCompat;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.viewpager2.widget.ViewPager2;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.viewholder.BaseViewHolder;
import com.jeremyliao.liveeventbus.LiveEventBus;
import com.scwang.smart.refresh.layout.SmartRefreshLayout;
import com.scwang.smart.refresh.layout.api.RefreshLayout;
import com.zahb.qadx.R;
import com.zahb.qadx.base.BaseApplication;
import com.zahb.qadx.base.BaseFragmentExt;
import com.zahb.qadx.model.DataLogin;
import com.zahb.qadx.model.MainFunc1;
import com.zahb.qadx.model.MainFunc2;
import com.zahb.qadx.net.RetrofitService;
import com.zahb.qadx.ui.activity.AllLecturerActivity;
import com.zahb.qadx.ui.activity.AnswerExercisesActivity;
import com.zahb.qadx.ui.activity.CurriculumListActivity;
import com.zahb.qadx.ui.activity.MyCourseActivity;
import com.zahb.qadx.ui.activity.NewsListActivity;
import com.zahb.qadx.ui.activity.VideoListActivity;
import com.zahb.qadx.ui.adapter.BannerAdapter;
import com.zahb.qadx.ui.view.adapter.MBaseAdapter;
import com.zahb.qadx.ui.view.adapter.MViewHolder;
import com.zahb.qadx.util.CompatHelper;
import com.zahb.qadx.util.Constant;
import com.zahb.qadx.util.DisplayUtil;
import com.zahb.qadx.util.ImageLoaderKt;
import com.zahb.qadx.util.JsonUtil;
import com.zahb.qadx.util.Tips;
import com.zhpan.bannerview.BannerViewPager;
import com.zhpan.bannerview.constants.PageStyle;
import com.zhpan.indicator.enums.IndicatorStyle;

import org.jetbrains.annotations.NotNull;

import java.util.ArrayList;
import java.util.List;

import io.reactivex.android.schedulers.AndroidSchedulers;

/**
 * Created by huwei.
 * Data 2020-09-29.
 * Time 09:28.
 */
public class HomeFragment extends BaseFragmentExt {

    private SmartRefreshLayout mRefreshLayout;
    public BannerViewPager<MainFunc2, BannerAdapter.BannerViewHolder> mBannerView;
    private BaseQuickAdapter<MainFunc2, BaseViewHolder> mItemsAdapter;
    private AdapterViewFlipper mAdfMessages;
    private MBaseAdapter<MainFunc2> mMessagesAdapter;

    private int mOldRootOrgId = -1;

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // 切换企业
        LiveEventBus.get(Constant.KEY_ROOT_ORG_ID_CHANGED, Integer.class)
                .observe(this, integer -> {
                    BaseApplication.getContext().getDataLogin().setCurrentOrg(integer);
                    if (getContext() != null) {
                        SharedPreferences sp = getContext().getSharedPreferences("AccountInfo", Context.MODE_PRIVATE);
                        sp.edit().putString("loginData", JsonUtil.getGson().toJson(BaseApplication.getContext().getDataLogin())).apply();
                    }
                    mRefreshLayout.autoRefresh();
                });
        // 登录成功
        LiveEventBus.get(Constant.KEY_USER_LOGIN_STATUS_CHANGED, DataLogin.class)
                .observe(this, dataLogin -> {
                    BaseApplication.getContext().setDataLogin(dataLogin);
                    mRefreshLayout.autoRefresh();
                });


    }

    @Override
    protected int getLayout() {
        return R.layout.fragment_home;
    }

    @Override
    protected void initViews(View rootView) {
        mRefreshLayout = rootView.findViewById(R.id.refresh_layout);
        mRefreshLayout.setEnableLoadMore(false);
        mRefreshLayout.setOnRefreshListener(this::loadData);
        initBannerView(rootView);
        initRvItems(rootView);
        initAdfMessages(rootView);
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        mRefreshLayout.autoRefresh();
    }

    private void loadData(RefreshLayout refreshLayout) {
        if (!TextUtils.isEmpty(BaseApplication.getContext().getToken())) {
//            RequestBody body = RequestBody.create(MediaType.parse("application/json"), json);
            addDisposable(RetrofitService.getNetService()
                    .getFuncList(3,"1")
                    .observeOn(AndroidSchedulers.mainThread())
                    .subscribe(response -> {
                        refreshLayout.finishRefresh();
                        if (response.getStatusCode() == 200) {
                            updateData(response.getData());
                        } else {
                            showBindToast(response.getErrorInfo());
                        }
                    }, throwable -> {
                        throwable.printStackTrace();
                        refreshLayout.finishRefresh();
                        Tips.RequestError(getActivity());
                    }));
        } else {
            refreshLayout.finishRefresh();
        }
    }

    private void updateData(List<MainFunc1> func1List) {
        int currentOrg = BaseApplication.getContext().getDataLogin().getCurrentOrg();
        if (mOldRootOrgId != currentOrg) {
            mOldRootOrgId = currentOrg;
            mAdfMessages.setVisibility(View.GONE);
            LinearLayoutCompat linearLayout = (LinearLayoutCompat) mAdfMessages.getParent();
            for (int i = 2; i < linearLayout.getChildCount(); i++) {
                View child = linearLayout.getChildAt(i);
                if (child instanceof FrameLayout) {
                    ((FrameLayout) child).removeAllViews();
                }
            }
        }

        int index = 0;
        for (MainFunc1 mainFunc1 : func1List) {
            switch (mainFunc1.getFunctionType()){
                case 1:// 轮播
                    mBannerView.refreshData( mainFunc1.getInfos());

                    break;
                case 2:// 金刚区
                    mItemsAdapter.setList(mainFunc1.getInfos());
                    break;
                case 3:// 推荐课程
                    index++;
                    if (CompatHelper.isEmpty(mainFunc1.getFunctionName()))
                        mainFunc1.setFunctionName("推荐学习");
                    replaceFragment(CurriculaFragment.newInstance(mainFunc1), CurriculaFragment.TAG, index);
                    break;
                case 4:// 新闻

                    index++;
                    replaceFragment(NewsFragment.newInstance(mainFunc1), NewsFragment.TAG, index);
                    break;
                case 5://讲师
                    index++;
                    replaceFragment(StarTeacherFragment.newInstance(mainFunc1), StarTeacherFragment.TAG, index);
                    break;
                case 6://音频
                    index++;
                    replaceFragment(AudiosFragment.newInstance(mainFunc1), AudiosFragment.TAG, index);
                    break;
                case 26://精选视频  1.3.3旧版10
                    index++;
                    replaceFragment(VideosFragment.newInstance(mainFunc1), VideosFragment.TAG, index);
                    break;
                case 13://     消息
                    List<MainFunc2> mainFunc2s = (List<MainFunc2>) mainFunc1.getInfos();
                    if (mainFunc2s == null) {
                        mainFunc2s = new ArrayList<>();
                    }
                    mMessagesAdapter.replaceAll(mainFunc2s);
                    mAdfMessages.setVisibility(View.VISIBLE);
                    mAdfMessages.startFlipping();
                    break;
                case 14://今日之星
                    index++;
                    replaceFragment(TodayStarFragment.newInstance(mainFunc1), TodayStarFragment.TAG, index);
                    break;
                case 24://宣传标语
                    index++;
                    replaceFragment(SloganFragment.newInstance(mainFunc1), SloganFragment.TAG, index);
                    break;

            }
        }
    }

    private void replaceFragment(Fragment newFragment, String tag, int index) {
        Fragment oldFragment = getChildFragmentManager().findFragmentByTag(tag);
        if (oldFragment != null) {
            getChildFragmentManager().beginTransaction().remove(oldFragment).commitNowAllowingStateLoss();
        }
        int id = getResources().getIdentifier(
                "fragment_container" + index, "id", mRootView.getContext().getPackageName());
        getChildFragmentManager().beginTransaction().replace(id, newFragment, tag).commitAllowingStateLoss();
    }

    // 初始化轮播控件
    private void initBannerView(View rootView) {
        mBannerView = rootView.findViewById(R.id.banner_view);
        mBannerView.setOrientation(ViewPager2.ORIENTATION_HORIZONTAL)
                .setAutoPlay(true)
                .setInterval(2000)
                .setScrollDuration(300)
                .setLifecycleRegistry(getLifecycle())
                .setIndicatorStyle(IndicatorStyle.CIRCLE)
                .setPageStyle(PageStyle.MULTI_PAGE_SCALE)
                .setIndicatorSliderRadius(DisplayUtil.dip2px(3f))
                .setIndicatorSliderColor(CompatHelper.getColor(R.color.gray_a1a1a1), CompatHelper.getColor(R.color.blue_409eff))
                .setAdapter(new BannerAdapter())
                .create();
    }

    // 初始化金刚区
    private void initRvItems(View rootView) {
        RecyclerView rvItems = rootView.findViewById(R.id.rv_items);
        rvItems.setLayoutManager(new GridLayoutManager(getContext(), 5) {//金刚区单条数量
            @Override
            public boolean canScrollVertically() {
                return false;
            }
        });
        mItemsAdapter = new BaseQuickAdapter<MainFunc2, BaseViewHolder>(R.layout.item_grid_home_item) {
            @Override
            protected void convert(@NotNull BaseViewHolder baseViewHolder, MainFunc2 mainFunc2) {
                ImageLoaderKt.loadImage(baseViewHolder.getView(R.id.iv_icon), mainFunc2.getIcon());
                baseViewHolder.setText(R.id.tv_title, mainFunc2.getTitle());
            }
        };
        mItemsAdapter.setOnItemClickListener((adapter, view, position) -> {
            MainFunc2 mainFunc2 = mItemsAdapter.getItem(position);
            if (TextUtils.isEmpty(mainFunc2.getMappingUrl())) {// 课程列表
                CurriculumListActivity.actionStart(getContext(), mainFunc2.getSourceId());
            } else {
                switch (mainFunc2.getMappingUrl()){
                    case "TaskList":// 任务列表
                        MyCourseActivity.actionStart(getContext());
                        break;
                    case "NewsList":// 新闻列表
                        NewsListActivity.actionStart(getContext(), mainFunc2.getSourceId());
                        break;
                    case "TeacherList":// 讲师列表
                        AllLecturerActivity.actionStart(getContext());
                        break;
                    case "VideoList":// 视频列表
                        VideoListActivity.actionStartVideo(getContext());
                        break;
                    case "AudioList"://音频列表
                        VideoListActivity.actionStartAudio(getContext());
                        break;
                    case "PracticeList"://答题练习
                        startActivity(new Intent(getActivity(), AnswerExercisesActivity.class));
                        break;

                }
            }
        });
        rvItems.setAdapter(mItemsAdapter);
    }
    // 初始化消息
    private void initAdfMessages(View rootView) {
        mAdfMessages = rootView.findViewById(R.id.avf_messages);
        mMessagesAdapter = new MBaseAdapter<MainFunc2>(rootView.getContext(), R.layout.item_home_message) {
            @Override
            public void convert(int position, MViewHolder holder, MainFunc2 item) {
                TextView tvMessage = holder.getView(R.id.tv_message);
                tvMessage.setText(item.getTitle());
            }
        };
        mAdfMessages.setAdapter(mMessagesAdapter);
        mAdfMessages.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                //MainFunc2 mainFunc2 = mMessagesAdapter.getItem(position);
                    MyCourseActivity.actionStart(getContext());

            }
        });
        mAdfMessages.setFlipInterval(3000);
        mAdfMessages.setInAnimation(getContext(), R.animator.view_flipper_in);
        mAdfMessages.setOutAnimation(getContext(), R.animator.view_flipper_out);
    }
}
